<template>
  <div class="p-6 space-y-4">
    <!-- Filter -->
    <el-card shadow="never" class="rounded-lg">
      <el-form :model="filters" label-position="top" class="search-form" @keyup.enter.native="onSearch">
        <el-row :gutter="12" align="bottom">
          <el-col :xs="24" :sm="12" :lg="5">
            <el-form-item label="设备位号或名称">
              <el-input v-model="filters.keyword" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="5">
            <el-form-item label="计划保养周期">
              <el-select v-model="filters.planCycle" clearable placeholder="请选择">
                <el-option v-for="c in planCycleOptions" :key="c" :label="c" :value="c" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="5">
            <el-form-item label="实际保养日期">
              <el-date-picker v-model="filters.actualDate" type="date" placeholder="选择日期" clearable class="w-full" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="5">
            <el-form-item label="所属部门">
              <el-select v-model="filters.department" clearable placeholder="请选择">
                <el-option v-for="d in departmentOptions" :key="d" :label="d" :value="d" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="4" class="flex justify-end items-end">
            <el-button type="primary" :loading="queryLoading" @click="onSearch">
              <el-icon class="mr-1"><Search /></el-icon>
              查询
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- Table -->
    <el-card shadow="never" class="rounded-lg">
      <div v-loading="tableLoading">
        <el-table :data="tableData" border>
          <el-table-column label="序号" type="index" width="80" align="center" :index="indexMethod" />
          <el-table-column label="设备位号" prop="code" min-width="120" />
          <el-table-column label="计划保养日期" prop="planDate" min-width="140" />
          <el-table-column label="实际保养日期" prop="actualDate" min-width="140" />
          <el-table-column label="保养类型" prop="maintainType" min-width="120" />
          <el-table-column label="保养项目" prop="item" min-width="160" />
          <el-table-column label="所属部门" prop="department" min-width="120" />
          <el-table-column label="状态" width="120" align="center">
            <template #default="scope">
              <el-tag :type="statusTagType(scope.row.status)">{{ scope.row.statusLabel }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="保养人" prop="maintainer" min-width="120" />
          <el-table-column label="操作" width="100" align="center">
            <template #default="scope">
              <el-link type="danger" @click="onDelete(scope.row)">删除</el-link>
            </template>
          </el-table-column>
          <template #empty>
            <el-empty description="暂无数据" />
          </template>
        </el-table>
      </div>

      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="onSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';

interface MaintainRecord {
  id: number;
  code: string;
  planDate: string;
  actualDate: string;
  maintainType: string;
  item: string;
  department: string;
  status: string;
  statusLabel: string;
  maintainer: string;
}

const filters = reactive({
  keyword: '',
  planCycle: '',
  actualDate: '' as any,
  department: ''
});

const planCycleOptions = ['月度', '季度', '半年', '年度'];
const departmentOptions = ['生产部门', '设备部', '安环部', '工艺部'];

const queryLoading = ref(false);
const tableLoading = ref(false);

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

const statusTagMap: Record<string, string> = {
  done: 'primary',
  delay: 'warning',
  pending: 'info'
};
const statusTagType = (s: string) => statusTagMap[s] ?? 'info';

const allRecords = ref<MaintainRecord[]>([]);

// generate 19 mock records
const mockInit = () => {
  const types = ['计划保养', '日常保养'];
  const items = ['更换润滑油', '紧固检查', '清洁维护', '更换密封件'];
  const statuses: Array<[string, string]> = [
    ['done', '完成'],
    ['delay', '延期'],
    ['pending', '未完成']
  ];
  const codes = ['VO101B', 'VO102A', 'PX305', 'HT450', 'SA600', 'IB220', 'EL330'];
  const names = ['王伟', '李娜', '张敏', '刘洋', '陈杰', '杨静', '黄磊', '周玲', '吴涛', '赵敏'];
  const list: MaintainRecord[] = [];
  let id = 1;
  const n = 7; // 固定条数，刷新不变
  for (let i = 0; i < n; i++) {
    const code = codes[i % codes.length];
    const type = types[i % types.length];
    const item = items[i % items.length];
    const dept = departmentOptions[i % departmentOptions.length];
    const [status, statusLabel] = statuses[i % statuses.length];
    const maintainer = names[i % names.length];
    const month = (i % 9) + 1;
    const planDate = `2025-${String(month).padStart(2, '0')}-15`;
    const actualDate = `2025-${String(month).padStart(2, '0')}-${10 + (i % 10)}`;
    list.push({ id: id++, code, planDate, actualDate, maintainType: type, item, department: dept, status, statusLabel, maintainer });
  }
  allRecords.value = list;
};

const tableData = ref<MaintainRecord[]>([]);

const indexMethod = (index: number) => (pagination.currentPage - 1) * pagination.pageSize + index + 1;

const applyFilter = () => {
  const keyword = filters.keyword.trim();
  const actualDateStr = filters.actualDate ? formatDate(filters.actualDate) : '';
  return allRecords.value.filter((r) => {
    const matchKeyword = keyword ? r.code.includes(keyword) : true;
    const matchCycle = filters.planCycle ? matchPlanCycle(r.planDate, filters.planCycle) : true;
    const matchActual = actualDateStr ? r.actualDate === actualDateStr : true;
    const matchDept = filters.department ? r.department === filters.department : true;
    return matchKeyword && matchCycle && matchActual && matchDept;
  });
};

const matchPlanCycle = (planDate: string, cycle: string) => {
  // Simplified mock: decide by month mapping
  const m = Number(planDate.slice(5, 7));
  if (cycle === '月度') return true;
  if (cycle === '季度') return [3, 6, 9, 12].includes(m);
  if (cycle === '半年') return [6, 12].includes(m);
  if (cycle === '年度') return m === 12;
  return true;
};

const formatDate = (d: any) => {
  if (!d) return '';
  const dt = new Date(d);
  const y = dt.getFullYear();
  const m = String(dt.getMonth() + 1).padStart(2, '0');
  const da = String(dt.getDate()).padStart(2, '0');
  return `${y}-${m}-${da}`;
};

const refreshTable = (list: MaintainRecord[]) => {
  pagination.total = list.length;
  const start = (pagination.currentPage - 1) * pagination.pageSize;
  tableData.value = list.slice(start, start + pagination.pageSize);
};

const fetchList = async (withBtnLoading = true) => {
  if (withBtnLoading) queryLoading.value = true;
  tableLoading.value = true;
  try {
    await new Promise((r) => setTimeout(r, 200));
    const filtered = applyFilter();
    refreshTable(filtered);
  } catch (e) {
    ElMessage.error('数据加载失败，请稍后重试');
  } finally {
    tableLoading.value = false;
    queryLoading.value = false;
  }
};

const onSearch = () => {
  pagination.currentPage = 1;
  fetchList();
};

const onSizeChange = (s: number) => {
  pagination.pageSize = s;
  pagination.currentPage = 1;
  fetchList(false);
};
const onPageChange = (p: number) => {
  pagination.currentPage = p;
  fetchList(false);
};

const onDelete = async (row: MaintainRecord) => {
  try {
    await ElMessageBox.confirm(`确认删除设备“${row.code}”的保养记录？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    tableLoading.value = true;
    await new Promise((r) => setTimeout(r, 200));
    allRecords.value = allRecords.value.filter((x) => x.id !== row.id);
    if ((pagination.currentPage - 1) * pagination.pageSize >= allRecords.value.length && pagination.currentPage > 1) {
      pagination.currentPage -= 1;
    }
    await fetchList(false);
    ElMessage.success('删除成功');
  } catch (e: any) {
    if (e !== 'cancel' && e !== 'close') ElMessage.error('删除失败，请稍后重试');
  } finally {
    tableLoading.value = false;
  }
};

onMounted(async () => {
  mockInit();
  await fetchList(false);
});
</script>
